﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using BLL;
using BO;
using Twitterizer;
using Logic.Enums;
using Sentiment;
using Facebook;

namespace Service
{
    class Program
    {
        static void Main(string[] args)
        {
            while (true)
            {
                RunService();
                //System.Threading.Thread.Sleep(60000);
            }
        }

        private static void RunService()
        {
            var accounts = Accounts.Get().Where(Accounts.Columns.TwKey, Actions.NotEqual, null).Select();
            foreach (var a in accounts)
                if (a.Type == Logic.Enums.AccountType.Twitter)
                    ProcessTwitter(a);

            var pages = FBPages.Get().Select();
            foreach (FBPage p in pages)
                 ProcessFacebook(p);

        }

        private static void ProcessTwitter(Account a)
        {
            string query = "@" + a.Name;
            int pageNumber = 0;

            var id = BLL.Accounts.GetLastPostID(a.ID);

            SearchOptions options = new SearchOptions()
            {
                PageNumber = pageNumber,
                NumberPerPage = 20,
            };

            if (id.HasValue)
                options.SinceId = id.Value;
            else options.SinceDate = DateTime.Now.AddDays(-1);

            TwitterResponse<TwitterSearchResultCollection> searchResult = TwitterSearch.Search(query, options);

            //while (searchResult.Result == RequestResult.Success)
            //{
                foreach (var tweet in searchResult.ResponseObject)
                {
                    if (BLL.Posts.Get().Where(Posts.Columns.ForeignID, Actions.Equal, tweet.Id.ToString()).SelectOne() != null)
                        return;

                    var post = new Post
                    {
                        AccountID = a.ID,
                        ForeignID = tweet.Id.ToString(),
                        Text = tweet.Text,
                        Type = (int)AccountType.Twitter,
                        FromUserName = tweet.FromUserScreenName
                    };
                    ProcessPost(post);
                    post.Insert();
                }

                
                Console.WriteLine();
            //}

            Console.Write("finished Account " + a.Name);
        }

        private static void ProcessPost(Post post)
        {
            var json = new AlchemyAPI.AlchemyAPI().TextGetTextSentiment(post.Text);
            var res = json.FromJson<RequestRes>();
            if (res.docSentiment != null)
            {
                post.Sentiment = res.docSentiment.score;

                if (post.Sentiment < 0)
                {
                    post.SapID = SapConnection.Con.CreateLead(string.Format("{0} wrote on {1}: {2}", post.FromUserName, (AccountType)post.Type, post.Text));
                    //if (!string.IsNullOrEmpty(post.SapID))
                    //    SapConnection.Con.CreateSubscription(post.SapID);
                }
            }
        }

        public static void ProcessFacebook(FBPage p)
        {
            FacebookClient fbClient = new FacebookClient(p.Token);

            var lastPost = Accounts.GetLastPost(p.ID);
            var filterString =  "since=" + (lastPost != null ? lastPost.Date: DateTime.Now.AddDays(-1)).ToString("yyyy-MM-ddTHH:mm:sszzz");

            dynamic res = fbClient.Get(String.Format("{0}/feed?{1}", p.ForeignID, filterString));
            var data = res.data;

            for (var i = 0; i < ((dynamic)data).Count; i++)
            {
                if (!string.IsNullOrEmpty(data[i].message))
                {
                    var post = new Post
                    {
                        Text = data[i].message,
                        PageID = p.ID,
                        Date = Convert.ToDateTime(data[i].created_time),
                        Type = (int)AccountType.Facebook,
                        ForeignID = data[i].id,
                        FromUserName = data[i].from.name
                    };

                    if (BLL.Posts.Get().Where(Posts.Columns.ForeignID, Actions.Equal, post.ForeignID).SelectOne() != null)
                        return;


                    ProcessPost(post);

                    post.Insert();
                }
            }
        }
    }
}
